// @Desc:
// @CreateTime: 2020/10/21
package visit

import (
    "github.com/gin-gonic/gin"
    . "mycrm.com/controller"
    mlog "mycrm.com/log"
    . "mycrm.com/module"
    "mycrm.com/module/customer"
    "mycrm.com/module/statistics"
    "mycrm.com/module/user"
    "mycrm.com/module/visit"
    "mycrm.com/utils"
    "net/http"
    "strconv"
)

// list
func List(c *gin.Context) {
    var (
        customerInfo  []map[string]interface{}
        pageSize      int
        total         int64 // 总条数
        curUserRoleId int
    )
    pageStr := c.Query("cur_page")
    pageNum, _ := strconv.Atoi(pageStr)
    name := c.Query("search_name")
    phone := c.Query("search_phone")
    endtime := c.Query("search_endtime")
    uid := c.Query("uid")
    // 首先判断下该用户的角色
    Db.Model(&user.CrmUser2role{}).Select("role_id").Where("user_id = ?", uid).Scan(&curUserRoleId)
    // mlog.Log.Info("role: ", curUserRoleId)
    tx := Db.Table("crm_customer as c")
    if name != "" {
        tx.Where("c.name = ?", name)
    }
    // 当前用户是 员工的话
    if curUserRoleId == 5 {
        tx.Where("c.user_id = ?", uid)
    }
    // 当前用户是组长, 只能查看该组的所有客户
    if curUserRoleId == 4 {
        var (
            userIdArr []int
            groupId int
        )
        Db.Model(&user.CrmUser{}).Where("id = ?", uid).Select("group_id").Scan(&groupId)
        Db.Model(&user.CrmUser{}).Where("group_id = ?", groupId).Select("id").Scan(&userIdArr)
        tx.Where("c.user_id IN (?)", userIdArr)
    }
    if phone != "" {
        tx.Where("c.phone = ?", phone)
    }
    if endtime != "" {
        tx.Where("c.next_visit_at <= ?", endtime)
    }
    tx.Count(&total).Select("c.*").Limit(pageSize).Offset((pageNum - 1) * pageSize).Order("created_at DESC").Scan(&customerInfo)
    mlog.Log.Info("customerInfo: ", customerInfo)
    c.JSON(http.StatusOK, &Response{
        Status:      1,
        Data:        customerInfo,
        Total:       int(total),
        CurrentPage: pageNum,
    })

}

// 回访客户
func CallCustomer(c *gin.Context) {
    var customerInfo customer.Customer
    if err := c.BindJSON(&customerInfo); err != nil {
        mlog.Log.Error("c.BindJSON(&customerInfo) is failed, err: ", err)
        return
    }
    mlog.Log.Info("reqData: ", customerInfo)
    resp := Response{
        Status: 1,
        Data:   "保存成功",
    }
    // err := Db.Model(&customer.Customer{}).Where("id = ?", customerInfo.ID).Update("next_visit_at", customerInfo.NextVisitAt).Error
    err := Db.Model(&customer.Customer{}).Where("id = ?", customerInfo.ID).Updates(&customer.Customer{NextVisitAt: customerInfo.NextVisitAt, ComeAt: customerInfo.ComeAt}).Error
    if err != nil {
        mlog.Log.Error("update is failed, err: ", err)
        resp.Status = 0
        resp.Data = err
    } else {
        // 添加本次回访内容
        // Db.Model(&visit.CrmVisitRecord{}).Create(map[string]interface{}{"customer_id": customerInfo.ID, "content": customerInfo.ExchangeContent})
        Db.Model(&visit.CrmVisitRecord{}).Create(&visit.CrmVisitRecord{
            CustomerId: customerInfo.ID,
            Content:    customerInfo.ExchangeContent,
            IsOk:       customerInfo.IsOk,
        })
    }
    c.JSON(http.StatusOK, &resp)

}

// 获取用户的回访记录
func GetVisitRecord(c *gin.Context) {
    customerId := c.Param("customerId")
    isAll := c.Param("isAll")
    var visitRecord []map[string]interface{}
    resp := Response{
        Status: 1,
    }
    if isAll == "yes" {
        curPage := c.Query("curPage")
        pageNum, _ := strconv.Atoi(curPage)
        var total int64
        Db.Model(&visit.CrmVisitRecord{}).Where("customer_id = ?", customerId).Count(&total).Offset((pageNum - 1) * 10).Limit(10).Order("created_at DESC").Scan(&visitRecord)
        resp.Total = int(total)
        resp.CurrentPage = pageNum
    } else { // no 的话表示显示最近 3 条
        Db.Model(&visit.CrmVisitRecord{}).Order("created_at DESC").Limit(3).Find(&visitRecord, "customer_id = ?", customerId)
    }
    resp.Data = visitRecord
    mlog.Log.Info("resp: ", visitRecord)
    c.JSON(http.StatusOK, &resp)
}

// 统计昨天天的访问量
func StatisticsVisitByDay() {
    curHour, isOk := utils.IsStatisticsVisit()
    if !isOk {
        mlog.Log.Infof("curHour %s is stop", curHour)
        return
    }
    today0, today23 := utils.GetCurDay0And23()
    last30Time := today0 - 30 * 24 * 3600
    // 删除 30 天以前的数据
    Db.Delete(&statistics.CrmStatistics{}, "created_at <= ?", last30Time)
    var userObjs []user.CrmUser
    // 按人进行统计
    Db.Model(&user.CrmUser{}).Select("id, name").Find(&userObjs, "status = 1")
    for _, userObj := range userObjs {
        var (
            visitsNum          int64 // 回访总数
            noVisitNum         int64 // 未完成的回访
            isOkVisitNum       int64 // 有效回访数量
            userHasCustomerNum int64 // 用户有多少个客户
        )
        // 查询该医生的今天的回访总数
        Db.Table("crm_customer as c").Joins("JOIN crm_visit_record as vr ON c.id = vr.customer_id").
            Where("c.user_id = ? AND vr.created_at BETWEEN ? and ?", userObj.ID, today0, today23).
            Distinct("vr.customer_id").
            Count(&visitsNum)
        // 获取未回访的数据
        Db.Table("crm_customer").Where("user_id = ? AND next_visit_at BETWEEN ? and ?", userObj.ID, today0, today23).
            Count(&noVisitNum)
        // 查询有效回访个数
        Db.Table("crm_customer as c").Joins("JOIN crm_visit_record as vr ON c.id = vr.customer_id").
            Where("c.user_id = ? AND vr.created_at BETWEEN ? and ? AND is_ok = 1", userObj.ID, today0, today23).
            Count(&isOkVisitNum)
        // 获取用户的所有客户
        Db.Table("crm_customer").Where("user_id = ?", userObj.ID).
            Count(&userHasCustomerNum)
        // 准备数据
        data := statistics.CrmStatistics{}
        data.VisitsDay = int(visitsNum)
        data.NoVisitsDay = int(noVisitNum)
        data.IsokVisitsDay = int(isOkVisitNum)
        data.CustomerTotal = int(userHasCustomerNum)
        // 先查询该用户当前用户当天是否新增, 如果存在就更新, 不存在就新增
        var hasNum int64
        Db.Model(&statistics.CrmStatistics{}).Where("user_id = ? AND created_at BETWEEN ? and ?", userObj.ID, today0, today23).Count(&hasNum)
        if hasNum > 0 {  // 存在更新
            Db.Model(&statistics.CrmStatistics{}).Where("user_id = ? AND created_at BETWEEN ? and ?", userObj.ID, today0, today23).Updates(&data)
        } else {
            data.UserId = userObj.ID
            data.Name = userObj.Name
            Db.Model(&statistics.CrmStatistics{}).Create(&data)
        }
    }
    // c.JSON(200, Response{
    //     Status:      1,
    //     Msg:         "ok",
    // })
}
